<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Plugin\OssController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class WechatController extends CommonController
{
    use OssController;
    //获取微信id
    public function getOpenid(Request $request){
        if($request->filled('code')){
            $utils = $this->wechatApp->getUtils();
            $response = $utils->codeToSession($request->code);
            try{
                if($response['openid']){
                    $user = User::query()
                        ->where('openid',$response['openid'])->first();
                    if($user){
//                        info('用户已经存在'.json_encode($user));
//                        if($user->pid==0&&$request->filled('pid')){
//                            $this->bindRelationShipById($user,$request->pid);
//                        }
                        $user->updated_at = now();
                        $user->save();
                        return $this->success($user);
                    }else{
                        $data['openid'] = $response['openid'];
//                        if($request->filled('pid')){
//                            $data['pid'] = $request->pid;
//                            $data['pid_collect'] = '-'.$request->pid.'-';
//                        }
                        $result = User::query()->create($data);
                        return $this->success($result);
                    }
                }
            }catch (Exception $exception){
                return $this->failed($exception->getMessage(),201);
            }
            return $this->success($response);
        }else{
            return $this->failed('请提交code',201);
        }
    }
    // 绑定上级关系
    public function setRemotePid(User $model, Request $request){
        $user = $model->query()->find($request->uid);

        if(!$user){
            return $this->failed('用户不存在',201);
        }
        $pid = $request->pid;
        if($pid == 0){
            $user->pid = 0;
            $user->pid_collect = '';
            $user->save();
            return $this->success('更新成功');
        }
        if($user->id == $pid){
            return [];
        }
        $puser = User::query()->select('id','pid','pid_collect','openid')->find($pid);
        if(!$puser){
            return [];
        }
        // 查找是否互为上下级
        if($puser->pid){ // 如果上级有上级情况
            // 要查找的元素
            $ustr = '-'.$user->id.'-';
            if (strpos($puser->pid_collect,$ustr) !== false){
                info('获取上下级关系'.$ustr.'...'.json_encode($puser->pid_collect));
                return [0,'不能互为上下级'];
            }
        }

        $arr['pid'] = $puser->id;
        $arr['pid_collect'] = '-'.$puser->id.'-';
//        if($puser->pid>0){
//            $arr['pid_collect'] = $puser->pid_collect.$puser->id.'-';
//        }else{
//
//        }
        User::query()->where('id',$user->id)->update($arr);
        return $this->success('更新数据成功');

    }
    // 通过code 获取用户手机号
    public function getPhoneByCode(Request $request){
        if(!$request->filled('code')||!$request->filled('openid')){
            return $this->failed('code 或者 openid 不存在',201);
        }
        $user = $this->getUser($request->openid);

        if(!$user){
            return $this->failed('用户不存在',201);
        }
        $data = [
            'code' => (string) $request->code,
        ];
        // $this->miniProgram->getClient()->withAccessToken('69_L1KhGAbpJqQB54LRwC3vBaNo14E6hvW50DP0D2vsOgGKCwqw-1IknQdQLsClJIh3nNJ6Y9LRuT0AdmlqrymWNQOnb6xZlPoEjfudWQKI4N2lqkfBusQFjfhHESADBNbADARPB');
        $response = $this->wechatApp->getClient()->postJson('wxa/business/getuserphonenumber', $data);
        $res = $response->toArray(false);
        if($res['errcode']==0){
            $user->wx_phone = $res['phone_info']['phoneNumber'];
            $user->save();
            return $this->success($user);
        }else{
            return $this->failed($res['errmsg']);
        }
    }
    public function update(User $model,Request $request){
        $data = $model->where('openid',$request->openid)->first();
        if(!$data){
            return $this->failed('用户不存在',201);
        }
        $res = $request->all();

        $data->update($res);
        return $this->success($data);
    }
    protected function getUser($openid){
        return User::query()->where('openid',$openid)->first();
    }
    public function getErcode(Request $request){
        $id = $request->input('goods_id',123);
        $data = [
            'scene' => $id,
            'page' => 'pages/index/index',
            'width' => 430,
            'check_path' => false,
            'env_version'=>'trial'
        ];

        $response = $this->wechatApp->getClient()->postJson('wxa/getwxacodeunlimit', $data);
        $path = $response->saveAs('/tmp/wxacode-123.png');
        $res = $response->toArray(false);
        return $this->success($res);
    }
    // 识别营业执照
    public function businessLicenseOCR(Request $request){
        $json = $this->bizlicense($request->img_url);
        return $this->success($json);
    }
    // 审核评论内容
    public function checkCommend(Request $request){
        $data = [
            'content'=>$request->contents,
            'version'=>2,
            'scene'=>2,
            'openid'=>$request->openid,
        ];
        $response = $this->wechatApp->getClient()->postJson('wxa/msg_sec_check', $data);
        $res = $response->toArray();
        return $this->success($res);
    }
    public function checkForum($title,$contet,$openid){
        $data = [
            'content'=>$contet,
            'version'=>2,
            'scene'=>2,
            'openid'=>$openid,
            'title'=>$title,
        ];
        $response = $this->wechatApp->getClient()->postJson('wxa/msg_sec_check', $data);
        return $response->toArray();
    }
    public function registerCode(Request $request){
        $num = $request->input('num',1);
        if($request->filled('mch_id')){
            for($i=0;$i<$num;$i++){
                $image_name = Str::random(10);
                $image = $this->setCode($image_name,$request);
            }
            return $this->success($image);
        }
    }
    // https://zhixuekejimap.oss-cn-beijing.aliyuncs.com
    protected function setCode($num,$request){
        $data = [
            'scene' => $num,
            'page' => 'pagesNd/xiangchu/index',
            'width' => 430,
            'check_path' => false,
        ];
        $path = 'mini_code';
        Storage::makeDirectory('public/'.$path);
        $response = $this->wechatApp->getClient()->postJson('wxa/getwxacodeunlimit', $data);
        $name = $request->mch_id.'_'.$num;
        $image = 'storage/'.$path.'/'.$name.'.png';
        $response->saveAs($image);
        $this->ossUpload($image,$image);
        Storage::delete('public/'.$path.'/'.$name.'.png');
        return $image;
    }
}
